/***********[to_cnf.cc]
Copyright (c) 2020, Fahiem Bacchus

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

***********/
#include <fstream>
#include <iostream>
#include <stdexcept>
#include "zfstream.h"

#include "Wcnf.h"

using std::cerr;
using std::cin;
using std::cout;
using std::runtime_error;
using std::string;

void print_usage(const char* name) {
  // clang-format off
  cerr << "USAGE: " << name
       << " [-h|-help|--help] [-hards] [--] [wcnf_file] >cnf_file\n"
       << "    reads a standardized wcnf_file (or <stdin> if wcnf_file is missing) and outputs a\n"
       << "    cnf file where all clauses, hard and soft, have been converted to ordinary clauses\n"
       << "    [-h|-help|--help]     print this help message\n"
       << "    [-hards]     discard the soft clauses outputting a cnf with the hard clauses only\n"
       << "                 initial \'h\' character starting the line\n"
       << "    [--]         double hyphen: regard very next argument as name of wcnf_file\n"
       << "                 irrespective of its format (e.g. file name can start with '-'\n"
       << "                 NOTE: '--' requires exactly one filename argument afterwards\n";
  // clang-format on
}

int main(int argc, char* argv[]) {
  // Operate as filter converting a maxsat wcnf instance into a cnf instance.

  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cerr.tie(0);

  string file_name;
  bool hards{false};

  try {
    for (int i = 1; i < argc; ++i) {
      string arg;
      arg = argv[i];
      if (arg == "-help" || arg == "-h" || arg == "--help") {
        print_usage(argv[0]);
        exit(1);
      }
      else if (arg == "-hards")
        hards = true;
      else if (arg == "--") {
        if (i + 2 != argc)
          throw runtime_error(
              "-- on command line must be followed by exactly one file name "
              "argument\n");
        else {
          file_name = argv[i + 1];
          break;
        }
      } else if (arg[0] == '-')
        throw runtime_error("Unknown option \"" + arg + "\"\n");
      else {
        if (!file_name.empty())
          throw runtime_error("extranous argument \"" + arg + "\"\n");
        file_name = arg;
      }
    }
  } catch (std::runtime_error& ex) {
    cerr << "Error: bad arguments " << ex.what();
    print_usage(argv[0]);
    exit(1);
  } catch (...) {
    print_usage(argv[0]);
    exit(1);
  }

  gzifstream ifs;
  if (!file_name.empty()) {
    ifs.open(file_name, std::ios::in | std::ios::binary);
    if (!ifs.is_open()) {
      cerr << "Error: could not open file \"" << file_name << "\"\n";
      exit(1);
    }
  }
  try {
    Wcnf theFormula;
    theFormula.loadFromStream(file_name.empty() ? cin : ifs);
    if (!file_name.empty()) ifs.close();
    theFormula.standardize();
    theFormula.outputCNF(cout, hards, file_name);
  } catch (std::runtime_error& ex) {
    cerr << "Error: " << ex.what();
    return 1;
  } catch (...) {
    cerr << "Error: unknown";
    return 1;
  }
  return 0;
}
